﻿Imports System.Net.NetworkInformation
Imports System.Threading
Imports HslCommunication
Imports HslCommunication.Profinet.Siemens
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Public Class FormMain
    Dim objUser As New clsUser
    Private WithEvents UcDigitalKeyboard1 As ucDigitalKeyboard
    Dim objProdSpec As New clsProdSpec
    Dim objPgdMesGt As New clsPgdMesGt
    Dim objFlbMst As New clsFlbMst
    Dim objDLDetailsMst As New clsDLDetailsMst
    Dim objDLMst As New clsDLMst
    Dim objGt As New clsGt
    Private objHWSetting As New clsHWSetting
    Private PLC As SiemensS7Net
    Private PLC_CONNECTED As Boolean = False
    Private objPLCDB As New clsFlBPLC
    Private PLC_TH As System.Threading.Thread '监控PLC
    Private Scan0_TH As System.Threading.Thread '监控法兰板料框是否在
    '控制线程开关，关了后，监控全部停止
    Private resetEventPLC As New ManualResetEvent(False)
    Delegate Sub monitorPlcDelegate(b_connectFLG As Boolean, b_readerFLG As Boolean, b_readerResult As String)
    Delegate Sub openRead0Delegatey() '扫描0

    Dim monitorPlcDe As New monitorPlcDelegate(AddressOf setView)

    Dim objGtResultDetails As New clsGtResultDetails
    Dim objGtNgReasonDetails As New clsGtNgReasonDetails
    Dim objGtNgDetails As New clsGtNgDetails
    Dim objGtProcedure As New clsGtProcedure
    Dim objGtProcedureDetails As New clsGtProcedureDetails
    Dim objFlbInfo As New clsFlbInfo
    Dim objWorkshopCurrent As New clsWorkshopCurrent
    Dim objGtPgdMesWorkReport As New clsGtPgdMesWorkReport
    Dim dt As DataTable

    Private objReader0 As clsReader
    Dim objReader0_IP As String
    Dim objReader0_PORT As String
    Dim dgvSelectedSysId As String = "-1"
    Dim dgvSelectedTV As String = String.Empty
    Dim dgvSelectedBatch As String = String.Empty
    Dim dgvSelectedOkNum As String = String.Empty

    Dim ping = New Net.NetworkInformation.Ping()

    '172.16.20.31
    Dim dttemp As New DataTable

    Dim httpHelper As New HttpHelper

    Dim warehousecode As String
    Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.WindowState = FormWindowState.Maximized
        If Not HslCommunication.Authorization.SetAuthorizationCode("98141214-0241-46e4-9dfe-a06f71c7edf4") Then

        End If
        If Not HslControls.Authorization.SetAuthorizationCode("ce5ade06-6f14-4b0d-b9c2-0d625664dc3f") Then

        End If
        dttemp.Columns.Add("b_gt_sys_id", GetType(String))
        dttemp.Columns.Add("ok_num", GetType(String))
        dttemp.Columns.Add("into_box_num", GetType(String))
        connectDB()
        getUserListByCJ()
        setConfigPLC()
        setData()
        initForm()
        Dim dt_flb As DataTable = objFlbMst.getFLBAllList()
        If dt_flb.Rows.Count > 0 Then
            cmbFLBType.DisplayMember = "mst_value"
            cmbFLBType.ValueMember = "size"
            cmbFLBType.DataSource = dt_flb
            cmbFLBMCode.DisplayMember = "material_code"
            cmbFLBMCode.ValueMember = "material_code"
            cmbFLBMCode.DataSource = dt_flb
        End If
        cmbFLBType.SelectedIndex = -1
        cmbFLBMCode.SelectedIndex = -1
    End Sub

    Private Sub connectDB()
        warehousecode = GetIniFile("WAREHOUSE", "warehouse_code", "", g_szInitFileName)
    End Sub

    Private Sub FormMain_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
        Dim dtFLB As DataTable = objHWSetting.selectByWorkshop(1)
        Dim drsSMQ0 As DataRow()
        drsSMQ0 = dtFLB.Select("equip_type_id='SMQ' and equip_id= 'Scaner0'")
        If String.IsNullOrEmpty(drsSMQ0(0)("ip")) = False Then
            objReader0_IP = drsSMQ0(0)("ip")
            objReader0_PORT = drsSMQ0(0)("port")
            Dim b_readerFLG As Boolean = False
            Try
                objReader0 = New clsReader(objReader0_IP, objReader0_PORT, Me, txtDLNo, PLC, "")
                objReader0.read()
                Dim pingResult As Net.NetworkInformation.PingReply = ping.Send(objReader0_IP)
                If pingResult.Status = Net.NetworkInformation.IPStatus.Success Then
                    b_readerFLG = True
                End If
                SetStatus0(b_readerFLG)
            Catch ex As Exception
                SetStatus0(False)
            End Try
        Else
            SetStatus0(False)
        End If
        PLC_TH = New Thread(AddressOf plcMonitorTimerThread)
        Scan0_TH = New Thread(AddressOf scan0inThread)
        resetEventPLC.Set()
        PLC_TH.Start()
        Scan0_TH.Start()
    End Sub

    Private Sub SetStatus0(_status As Boolean)
        If _status Then
            lblReaderStatus.Text = "读码器连接成功"
            lblReaderStatus.ForeColor = Color.Green
        Else
            lblReaderStatus.Text = "读码器连接失败"
            lblReaderStatus.ForeColor = Color.Red
        End If
        Me.Refresh()
    End Sub

    Private Sub getUserListByCJ()
        Dim dtUser As DataTable = objUser.getUserListByCJ(1)
        cmbOper.DisplayMember = "user_name"
        cmbOper.ValueMember = "user_id"
        cmbOper.DataSource = dtUser
        If String.IsNullOrEmpty(g_Current_UserID) = False Then
            cmbOper.SelectedValue = g_Current_UserID
        End If
        cmbOper.Enabled = False
    End Sub

    Public Sub initForm()
        Dim dttxx As DataTable = objWorkshopCurrent.GetListByWorkShopIdAndCurrentSection("1", "FLBZP")
        Dim dtProdS As DataTable = objProdSpec.selectAllbySpecId(dttxx.Rows(0)("support_model"))
        If dtProdS.Rows.Count > 0 Then
            cmb_MesPlan.Items.Clear()
            cmb_MesPlan.Items.Add(dtProdS.Rows(0)("mst_name"))
            cmb_MesPlan.Tag = dttxx.Rows(0)("b_pgd_sys_id")
            cmb_MesPlan.SelectedIndex = 0
            Dim dttPgdGtMes As DataTable = objPgdMesGt.getListById(dttxx.Rows(0)("b_pgd_sys_id"))
            If dttPgdGtMes.Rows.Count > 0 Then
                If dttPgdGtMes.Rows(0)("material_code").Equals(DBNull.Value) = False Then
                    Dim dttFlbMst As DataTable = objFlbMst.getAllList(dttPgdGtMes.Rows(0)("material_code"))
                    If dttFlbMst.Rows.Count > 0 Then
                        cmbFLBType1.Items.Clear()
                        cmbFLBType1.Items.Add(dttFlbMst.Rows(0)("mst_value"))
                        cmbFLBType1.SelectedIndex = 0
                        lblSize1.Text = dttFlbMst.Rows(0)("size")
                        cmbFLBMCode1.Items.Clear()
                        cmbFLBMCode1.Items.Add(dttFlbMst.Rows(0)("material_code"))
                        cmbFLBMCode1.SelectedIndex = 0
                    End If
                End If
                lblPlanCount.Text = dttxx.Rows(0)("oper_count")
            End If
        Else
            cmb_MesPlan.Items.Clear()
            cmb_MesPlan.Text = ""
            cmbFLBType1.Items.Clear()
            cmbFLBType1.Text = ""
            cmbFLBMCode1.Items.Clear()
            cmbFLBMCode1.Text = ""
            lblSize1.Text = ""
            lblPlanCount.Text = "0"
        End If
    End Sub

    Private Sub setConfigPLC()
        Dim objHW As New clsHWSetting
        Dim jxb_plc_ip As String = ""
        Dim jxb_plc_port As String = "102"
        Dim dtJXB As DataTable
        '取得硬件设置里的法兰板的IP和端口
        dtJXB = objHW.selectByType(1, "FLB")

        If IsNothing(dtJXB) = False AndAlso dtJXB.Rows.Count > 0 Then
            jxb_plc_ip = dtJXB(0)("ip")
            jxb_plc_port = dtJXB(0)("port")
            '设置PLC的IP和端口
            PLC = New SiemensS7Net(SiemensPLCS.S1200)
            PLC.IpAddress = jxb_plc_ip
            PLC.Port = jxb_plc_port
            PLC.SetPersistentConnection()
        End If
    End Sub

    Public Sub plcMonitorTimerThread()
        While True
            '连接测试
            'Dim plcConnectFLg As OperateResult = PLC.ConnectServer()
            'Dim b_connectFLG As Boolean = plcConnectFLg.IsSuccess
            Dim b_connectFLG As Boolean = PLC.ReadBool("DB30.DBX0.0").IsSuccess
            Dim b_readerResult As String = PLC.ReadBool("DB30.DBX0.0").Content
            Dim _result As IAsyncResult
            Dim b_readerFLG As Boolean = False
            If IsNothing(objReader0) Then
                objReader0 = New clsReader(objReader0_IP, objReader0_PORT, Me, txtDLNo, PLC, "")
            End If
            Dim pingResult As Net.NetworkInformation.PingReply = ping.Send(objReader0.IP)
            If pingResult.Status = Net.NetworkInformation.IPStatus.Success Then
                If IsNothing(objReader0) Then
                    objReader0 = New clsReader(objReader0_IP, objReader0_PORT, Me, txtDLNo, PLC, "")
                End If
                b_readerFLG = True
            Else
                objReader0 = Nothing
            End If

            '查一下当前预组装的情况，如果规格一致，就放接驳工位，否则，放仓库
            If dgv.SelectedRows.Count > 0 Then
                If b_connectFLG Then
                    Dim flbTy As String = dgv.SelectedRows(0).Cells("type_value").Value.ToString()
                    Dim dtwc As DataTable = objWorkshopCurrent.getListByWorkshop(0)
                    If dtwc.Rows.Count = 1 Then
                        If dtwc.Rows(0)("flb_type").ToString().Equals(flbTy) Then
                            PLC.Write("DB30.DBX0.6", True)
                            PLC.Write("DB30.DBX0.7", False)
                        Else
                            PLC.Write("DB30.DBX0.7", True)
                            PLC.Write("DB30.DBX0.6", False)
                        End If
                    End If
                End If
            End If

            _result = Me.Invoke(monitorPlcDe, b_connectFLG, b_readerFLG, b_readerResult)
            Thread.Sleep(500)
        End While
    End Sub

    Private Sub setView(b_connectFLG As Boolean, b_readerFLG As Boolean, b_readerResult As String)
        '如果连接成功
        If b_connectFLG Then
            lan1.LanternBackground = Color.LimeGreen
            'objPLCDB.insertLog("linkFLBPLC", "法兰板连接成功")
            PLC_CONNECTED = True
        Else
            lan1.LanternBackground = Color.Red '红色
            'objPLCDB.insertLog("linkFLBPLC", "法兰板连接失败1")
            PLC_CONNECTED = False
            LabelControl1.ForeColor = Color.Black
            'LabelControl1.Text = "PLC设定结果"
            LabelControl1.Refresh()
        End If
        If b_readerFLG Then
            lblReaderStatus.Text = "读码器连接成功"
            lblReaderStatus.ForeColor = Color.Green
            lblreaderResult.Text = b_readerResult
        Else
            lblReaderStatus.Text = "读码器连接失败"
            lblReaderStatus.ForeColor = Color.Red
            lblreaderResult.Text = b_readerResult
        End If
        lan1.Refresh()
        lblReaderStatus.Refresh()
    End Sub

    Private Sub txtOper_Click(sender As Object, e As EventArgs)
        Process.Start("C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe")
        'Process.Start("C:\windows\system32\osk.exe")
    End Sub

    Private Sub btnFresh_Click(sender As Object, e As EventArgs) Handles btnFresh.Click
        setData()
    End Sub

    Public Sub setData()
        dt = objGt.getCurrentGt("1", "2", "2")
        dt.Columns.Add("oper_type_name")
        'Dim datarow As DataRow = dt.NewRow()
        'dt.Rows.InsertAt(datarow, dt.Rows.Count)
        If dt.Rows.Count > 0 Then
            For Each row As DataRow In dt.Rows
                If row("oper_type") = "0" Then
                    row("oper_type_name") = "骨架板"
                Else
                    row("oper_type_name") = "法兰板"
                End If
            Next
        End If
        dgv.AutoGenerateColumns = False
        dgv.DataSource = dt
        For index = 0 To dgv.Rows.Count - 1
            dgv.Rows(index).Selected = False
        Next
        For index = 0 To dgv.Rows.Count - 1
            If dgv.Rows(index).Cells("sys_id").Value.ToString() = dgvSelectedSysId Then
                dgv.Rows(index).Selected = True
                Exit For
            End If
        Next
        'If dgv.Rows.Count > 0 Then
        '    If dgvSelectedSysId = "-1" Then
        '        dgv.Rows(0).Selected = True
        '    End If
        'End If
    End Sub

    Private Sub scan0inThread()
        resetEventPLC.WaitOne()
        Dim openReader0 As New openRead0Delegatey(AddressOf objReader0.read)
        Dim _result2 As IAsyncResult
        While True
            If PLC_CONNECTED = True Then
                If PLC.ReadBool("DB30.DBX0.0").Content = False Then
                    Dim _result As OperateResult(Of TimeSpan) = PLC.Wait("DB30.DBX0.0", True, 100, -1)
                    If _result.IsSuccess = True Then
                        _result2 = openReader0.BeginInvoke(Nothing, Nothing)
                        openReader0.EndInvoke(_result2)
                    End If
                End If
            End If
            Thread.Sleep(500)
        End While
    End Sub

    Public Sub setDgvOperData()
        If dgv.SelectedRows.Count > 0 Then
            Dim dtProcedure As DataTable = objGtProcedure.selectGtProcedure(dgv.Rows(dgv.CurrentRow.Index).Cells("sys_id").Value.ToString(), "1")
            dgvIntoAll.AutoGenerateColumns = False
            dgvIntoAll.DataSource = dtProcedure
            Dim dtOper As DataTable = objGtProcedureDetails.getGtProcedureDetailsList(dgv.SelectedRows(0).Cells("sys_id").Value.ToString(), "1")
            dgvOper.AutoGenerateColumns = False
            dgvOper.DataSource = dtOper
        End If
    End Sub

    Public Sub SetDgvResultData()
        Dim dtResult As DataTable = objGtResultDetails.getGtResultDetailsList(dgv.Rows(dgv.CurrentRow.Index).Cells("sys_id").Value.ToString(), "2")
        dgvOKNG.AutoGenerateColumns = False
        dgvOKNG.DataSource = dtResult
    End Sub

    Public Sub setDgvNgOperData()
        Dim dtNgOper As DataTable = objGtNgReasonDetails.getGtNgDetailsList(dgv.Rows(dgv.CurrentRow.Index).Cells("sys_id").Value.ToString(), "2")
        dgvNgOper.AutoGenerateColumns = False
        dgvNgOper.DataSource = dtNgOper
        Dim dtFlbMst As DataTable = objFlbMst.selectFlbByVal(dgvSelectedTV)
        If rdoZM.Checked Then
            txt_Max_Count.Value = dtFlbMst.Rows(0)("count_down")
        End If
        If rdoFM.Checked Then
            txt_Max_Count.Value = dtFlbMst.Rows(0)("count_up")
        End If
        Dim dtt As DataTable = objFlbInfo.getFlbInfoListByGtSysId(dgvSelectedSysId)
        Dim dttetails As DataTable = objFlbInfo.getFlbInfoDetailsListByGtSysId(dgvSelectedSysId)
        txtAssembledAll.Value = Integer.Parse(dtt.Rows(0)("piece_num_all").ToString()) + Integer.Parse(dttetails.Rows(0)("piece_num_all").ToString())
        If dgvOKNG.Rows.Count > 0 Then
            txtAssemblableAll.Value = Integer.Parse(dgvOKNG.Rows(0).Cells("C_ok_num").Value.ToString()) - (Integer.Parse(dtt.Rows(0)("piece_num_all").ToString()) + Integer.Parse(dttetails.Rows(0)("piece_num_all").ToString()))
        Else
            txtAssemblableAll.Value = 0
        End If
    End Sub

    Private Sub dgv_MouseClick(sender As Object, e As MouseEventArgs) Handles dgv.MouseClick
        'For index = 0 To dgv.Rows.Count - 1
        '    dgv.Rows(index).Selected = False
        'Next
        'dgvSelectedSysId = "-1"
        If dgv.Rows.Count > 0 Then
            dgvSelectedSysId = dgv.Rows(dgv.CurrentRow.Index).Cells("sys_id").Value.ToString()
            dgvSelectedTV = dgv.Rows(dgv.CurrentRow.Index).Cells("type_value").Value.ToString()
            dgvSelectedBatch = dgv.Rows(dgv.CurrentRow.Index).Cells("batch_no").Value.ToString()
            dgvSelectedOkNum = dgv.Rows(dgv.CurrentRow.Index).Cells("ok_num").Value.ToString()
            Dim dtFlbMst As DataTable = objFlbMst.selectFlbByVal(dgvSelectedTV)
            cmbFLBType.Text = dgv.Rows(dgv.CurrentRow.Index).Cells("type_value").Value.ToString()
            lblSize.Text = cmbFLBType.SelectedValue.ToString()
            cmbFLBMCode.Text = dgv.Rows(dgv.CurrentRow.Index).Cells("material_code").Value.ToString()
            If rdoZM.Checked Then
                txt_Max_Count.Value = dtFlbMst.Rows(0)("count_down")
            End If
            If rdoFM.Checked Then
                txt_Max_Count.Value = dtFlbMst.Rows(0)("count_up")
            End If
            setDgvOperData()
            SetDgvResultData()
            setDgvNgOperData()
            PlcWriteBase()
        End If
    End Sub

    Private Sub btnNg_Click(sender As Object, e As EventArgs) Handles btnNg.Click
        If dgvOper.SelectedRows.Count > 0 Then
            Dim formNgOper As New FormNgOper()
            formNgOper.ty = "1"
            formNgOper.b_gt_sys_id = dgvSelectedSysId
            formNgOper.current_procedure_No = 2
            formNgOper.ng_num_all = dgvOKNG.SelectedRows(0).Cells("Co_ng_num").Value.ToString()
            formNgOper.oper_num_all = dgvIntoAll.SelectedRows(0).Cells("Col_oper_num").Value.ToString()
            formNgOper.ShowDialog(Me)
        End If
    End Sub

    Private Sub btnValidity_Click(sender As Object, e As EventArgs) Handles btnValidity.Click
        If dgvNgOper.SelectedRows.Count > 0 Then
            If dgvNgOper.SelectedRows(0).Cells("Colu_validity").Value.ToString().Equals("1") Then
                If MsgBox("确认要进行作废吗？", vbYesNo, "提示") = vbYes Then
                    Dim sys_id As String = dgvNgOper.SelectedRows(0).Cells("Colu_sys_id").Value.ToString()
                    Dim procedure_no As String = dgvNgOper.SelectedRows(0).Cells("Colu_procedure_no").Value.ToString()
                    Dim b_gt_sys_id As String = dgvNgOper.SelectedRows(0).Cells("Colu_b_gt_sys_id").Value.ToString()
                    Dim ng_num As String = dgvNgOper.SelectedRows(0).Cells("Colu_ng_num").Value.ToString()
                    Dim rtn As Integer = objGtNgReasonDetails.updateValidity(sys_id, ng_num, b_gt_sys_id, procedure_no, cmbOper.Text.Trim())
                    If rtn <> -2 Then
                        MsgBox("作废成功")
                        SetDgvResultData()
                        setDgvNgOperData()
                    Else
                        MsgBox("作废失败")
                    End If
                End If
            Else
                MsgBox("该记录已作废")
            End If
        End If
    End Sub

    Public Sub PlcWriteBase()
        Dim type_val As String = dgvSelectedTV
        Dim ty_val As Integer = 0
        If type_val.Contains("500") Then
            ty_val = 1
        ElseIf type_val.Contains("600") Then
            ty_val = 1
        ElseIf type_val.Contains("700") Then
            ty_val = 2
        ElseIf type_val.Contains("800") Then
            ty_val = 2
        ElseIf type_val.Contains("900") Then
            ty_val = 3
        ElseIf type_val.Contains("1000") Then
            ty_val = 3
        End If

        '写plc
        If PLC_CONNECTED Then
            Dim flbType As String = PLC.ReadString("DB30.DBX22.0").Content
            Dim boxType As Byte = PLC.ReadByte("DB30.DBB16").Content
            Dim planNum As Int16 = PLC.ReadInt16("DB30.DBW18").Content
            If type_val = flbType And Byte.Parse(ty_val) = boxType And Int16.Parse(dgvSelectedOkNum) = planNum Then
                LabelControl1.ForeColor = Color.Green
                LabelControl1.Text = "已设定成功"
            Else
                If PLC.Write("DB30.DBX22.0", type_val).IsSuccess And
                PLC.Write("DB30.DBB16", Byte.Parse(ty_val)).IsSuccess And
                PLC.Write("DB30.DBW18", Int16.Parse(dgvSelectedOkNum)).IsSuccess Then
                    LabelControl1.ForeColor = Color.Green
                    LabelControl1.Text = "新设定成功"
                    If PLC.Write("DB30.DBX20.2", True).IsSuccess = False Then
                        PLC.Write("DB30.DBX20.2", True)
                        Thread.Sleep(2000)
                        If PLC.Write("DB30.DBX20.2", False).IsSuccess = False Then
                            PLC.Write("DB30.DBX20.2", False)
                        End If
                    End If
                    If PLC.Write("DB30.DBX20.3", True).IsSuccess = False Then
                        PLC.Write("DB30.DBX20.3", True)
                        Thread.Sleep(2000)
                        If PLC.Write("DB30.DBX20.3", False).IsSuccess = False Then
                            PLC.Write("DB30.DBX20.3", False)
                        End If
                    End If
                Else
                    LabelControl1.ForeColor = Color.Red
                    LabelControl1.Text = "设定失败"
                End If
            End If
        Else
            LabelControl1.Text = "无法与PLC通讯"
        End If

    End Sub

    Private Sub btnResetPlc_Click(sender As Object, e As EventArgs) Handles btnResetPlc.Click
        '写plc
        If PLC_CONNECTED Then
            If PLC.Write("DB30.DBX22.0", "").IsSuccess And
                PLC.Write("DB30.DBB16", Byte.Parse(0)).IsSuccess And
                PLC.Write("DB30.DBW18", 0).IsSuccess Then
                LabelControl1.ForeColor = Color.Green
                LabelControl1.Text = "重置设定成功"
            Else
                LabelControl1.ForeColor = Color.Red
                LabelControl1.Text = "重置设定失败"
            End If
        End If
    End Sub

    Private Sub btnReader_Click(sender As Object, e As EventArgs) Handles btnReader.Click
        If IsNothing(objReader0) = False Then
            objReader0.read()
        End If
    End Sub

    Private Sub btnDirectionReader_Click(sender As Object, e As EventArgs) Handles btnDirectionReader.Click
        If PLC_CONNECTED Then
            Dim xx = PLC.ReadByte("DB30.DBB1").Content '翻转设定
            If xx = 0 Then
                rdoZM.Checked = True
            End If
            If xx = 1 Then
                rdoFM.Checked = True
            End If
        End If
    End Sub

    Private Sub txtDLNo_Click(sender As Object, e As EventArgs) Handles txtDLNo.Click
        Process.Start("C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe")
        'Process.Start("C:\windows\system32\osk.exe")
    End Sub


    Private Sub txtDLNo_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtDLNo.KeyPress
        If e.KeyChar = vbCr Then
            If String.IsNullOrEmpty(txtDLNo.Text.Trim()) = False Then
                txtDLNo.Text = txtDLNo.Text.Trim().ToUpper()
                'Dim rtn_Count As Integer = search()
                'If rtn_Count = 1 Then
                '    SendKeys.Send("{Tab}")
                'Else
                '    If rtn_Count = 0 Then
                '        MsgBox("此条码信息不存在")
                '    Else
                '        MsgBox("此条码信息存在多条记录")
                '    End If
                'End If
            Else
                MsgBox("请扫描或输入条码值")
            End If

        End If
    End Sub

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        If dgv.SelectedRows.Count > 0 Then
            If txt_num.Value > 0 Then
                Dim b_success As Boolean = True
                If dttemp.Rows.Count > 0 Then
                    For index = 0 To dttemp.Rows.Count - 1
                        If dttemp.Rows(index)("b_gt_sys_id").Equals(dgv.SelectedRows(0).Cells("sys_id").Value.ToString()) Then
                            b_success = False
                            Exit For
                        End If
                    Next
                End If
                If b_success Then
                    dttemp.Rows.Add(dgv.SelectedRows(0).Cells("sys_id").Value.ToString(),
                                dgv.SelectedRows(0).Cells("ok_num").Value.ToString(),
                                txt_num.Value.ToString())
                    txt_current_all_num.Value = txt_current_all_num.Value + txt_num.Value
                    dgvAssembling.AutoGenerateColumns = False
                    dgvAssembling.DataSource = dttemp
                Else
                    lblError.Text = "该入料信息及装框数量已添加！"
                End If
            Else
                lblError.Text = "装配数量需 > 0！"
            End If

        Else
            lblError.Text = "请选择当前生产信息！"
        End If

    End Sub

    Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
        If dgvAssembling.Rows.Count > 0 Then
            If MsgBox("您确定要进行删除吗？", MsgBoxStyle.OkCancel, "提示") = MsgBoxResult.Ok Then
                txt_current_all_num.Value = txt_current_all_num.Value - dttemp.Rows(dgvAssembling.SelectedRows(0).Index)("into_box_num")
                dttemp.Rows.RemoveAt(dgvAssembling.SelectedRows(0).Index)
            End If
        End If
    End Sub

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click, btnSave2.Click
        If dgv.SelectedRows.Count <= 0 Then
            lblError.Text = "请选择需装配的法兰板！"
            Exit Sub
        End If
        If dgv.SelectedRows(0).Cells("material_code").Value.ToString().Equals(cmbFLBMCode1.Text.ToString()) = False Then
            lblError.Text = "当前生产法兰板与生产设定不一致！"
            Exit Sub
        End If
        Dim b_dl As Boolean = False
        Dim b_dlMst As Boolean = False
        If String.IsNullOrEmpty(txtDLNo.Text.Trim()) = False Then
            Dim ddx As String = txtDLNo.Text.ToUpper().Substring(0, 1)
            If ddx.Equals("F") Then
                Dim dtDL As DataTable = objDLDetailsMst.selectFlbDLByBarCode(txtDLNo.Text.ToUpper().Trim())
                If dtDL.Rows.Count > 0 Then
                    For index = 0 To dtDL.Rows.Count - 1
                        If dgv.SelectedRows(0).Cells("type_value").Value.ToString().Contains(dtDL.Rows(index)("type_value")) Then
                            b_dl = True
                        End If
                    Next
                    If b_dl = False Then
                        lblError.Text = "该吊篮与生产的规格型号不匹配，请核查！"
                        Exit Sub
                    End If
                    Dim dtDlMst As DataTable = objDLMst.selectFlbDLByBarCode(txtDLNo.Text.ToUpper().Trim())
                    If dtDlMst.Rows(0)("status").ToString().Equals("0") Then
                        b_dlMst = True
                    Else
                        lblError.Text = "该吊篮号不为空闲状态，无法进行装配"
                        Exit Sub
                    End If
                    Dim dtfii As DataTable = objFlbInfo.getListByDlNoAndStatus(txtDLNo.Text.ToUpper().Trim(), "2")
                    If dtfii.Rows.Count = 0 Then
                        b_dlMst = True
                    Else
                        lblError.Text = "此吊篮号有未使用完的记录，无法进行装配，请核查！"
                        Exit Sub
                    End If
                Else
                    lblError.Text = "未找到该吊篮号，请核查"
                    Exit Sub
                End If
            Else
                lblError.Text = "该吊篮号不属于法兰板的吊篮号，请核查"
                Exit Sub
            End If
        Else
            lblError.Text = "请扫描或输入吊篮号！"
            Exit Sub
        End If
        If dgvAssembling.Rows.Count < 1 Then
            lblError.Text = "请添加料框数量！"
            Exit Sub
        End If
        If b_dl And b_dlMst Then
            If txt_num.Value > 0 Then
                Dim operable_num = 0
                If dgvAssembling.Rows.Count > 1 Then
                    operable_num = txt_Max_Count.Value
                Else
                    If txt_Max_Count.Value < txtAssemblableAll.Value Then
                        operable_num = txt_Max_Count.Value
                    Else
                        operable_num = txtAssemblableAll.Value
                    End If
                End If
                If txt_num.Value <= operable_num Then
                    If txt_current_all_num.Value <= operable_num Then
                        Dim flb_ingo As New entity_flb_info
                        'flb_ingo.sys_id = _sys_id
                        flb_ingo.dl_no = txtDLNo.Text.ToUpper().Trim()
                        flb_ingo.batch_no = dgvSelectedBatch
                        flb_ingo.pgd_id = cmb_MesPlan.Tag.ToString()
                        flb_ingo.support_model = String.Empty
                        flb_ingo.material_code = cmbFLBMCode.Text.Trim()
                        flb_ingo.flb_type = dgvSelectedTV
                        flb_ingo.piece_num = txt_current_all_num.Value
                        If rdoZM.Checked Then
                            flb_ingo.which_side = "0"
                        Else
                            flb_ingo.which_side = "1"
                        End If
                        flb_ingo.status = "0"
                        flb_ingo.oper = cmbOper.Text.Trim()
                        Dim rtn As Integer
                        If dgvAssembling.Rows.Count = 1 Then
                            flb_ingo.b_gt_sys_id = dgv.SelectedRows(0).Cells("sys_id").Value.ToString()
                            rtn = objFlbInfo.save(flb_ingo)
                        ElseIf dgvAssembling.Rows.Count > 1 Then
                            'flb_ingo.b_gt_sys_id = dgv.SelectedRows(0).Cells("sys_id").Value.ToString()
                            flb_ingo.b_gt_sys_id = "0"
                            rtn = objFlbInfo.save(flb_ingo, dttemp)
                        End If
                        If rtn = -2 Then
                            lblError.Text = "保存失败"
                        Else
                            txtDLNo.Focus()
                            dttemp.Rows.Clear()
                            dgvAssembling.Refresh()
                            txt_num.Value = 0
                            txt_current_all_num.Value = 0
                            If sender.tag = 0 Then
                                '写plc 满筐放行
                                If PLC_CONNECTED Then
                                    If PLC.Write("DB30.DBX0.1", True).IsSuccess Then
                                        lblFX.Text = "放行1：True"
                                        Threading.Thread.Sleep(1000)
                                        If PLC.Write("DB30.DBX0.1", False).IsSuccess = False Then
                                            PLC.Write("DB30.DBX0.1", False)
                                        End If
                                    End If
                                Else
                                    PLC.Write("DB30.DBX0.1", True)
                                    lblFX.Text = "放行2：True"
                                    Threading.Thread.Sleep(1000)
                                    If PLC.Write("DB30.DBX0.1", False).IsSuccess = False Then
                                        PLC.Write("DB30.DBX0.1", False)
                                    End If
                                End If
                            End If
                            lblError.Text = "保存成功"
                            txtDLNo.Text = String.Empty
                            setData()
                            setDgvNgOperData()
                        End If
                    Else
                        lblError.Text = "当前料框已装配总数量 <= 单框可装配数量"
                    End If
                Else
                    If txt_Max_Count.Value < txtAssemblableAll.Value Then
                        lblError.Text = "装配数量需 <= 单框可装配数量"
                    Else
                        lblError.Text = "装配数量需 <= 总共可装配数量"
                    End If
                End If
            Else
                lblError.Text = "装配数量需 > 0"
            End If
        End If
    End Sub

    Private Sub btnSave1_Click(sender As Object, e As EventArgs) Handles btnSave1.Click
        If dgv.SelectedRows.Count <= 0 Then
            lblError.Text = "请选择需装配的法兰板！"
            Exit Sub
        End If
        Dim b_dl As Boolean = False
        Dim b_dlMst As Boolean = False
        If String.IsNullOrEmpty(txtDLNo.Text.Trim()) = False Then
            Dim ddx As String = txtDLNo.Text.ToUpper().Substring(0, 1)
            If ddx.Equals("F") Then
                Dim dtDL As DataTable = objDLDetailsMst.selectFlbDLByBarCode(txtDLNo.Text.ToUpper().Trim())
                If dtDL.Rows.Count > 0 Then
                    For index = 0 To dtDL.Rows.Count - 1
                        If dgv.SelectedRows(0).Cells("type_value").Value.ToString().Contains(dtDL.Rows(index)("type_value")) Then
                            b_dl = True
                        End If
                    Next
                    If b_dl = False Then
                        lblError.Text = "该吊篮与生产的规格型号不匹配，请核查！"
                        Exit Sub
                    End If
                    Dim dtDlMst As DataTable = objDLMst.selectFlbDLByBarCode(txtDLNo.Text.ToUpper().Trim())
                    If dtDlMst.Rows(0)("status").ToString().Equals("0") Then
                        b_dlMst = True
                    Else
                        lblError.Text = "该吊篮号不为空闲状态，无法进行装配"
                        Exit Sub
                    End If
                    Dim dtfii As DataTable = objFlbInfo.getListByDlNoAndStatus(txtDLNo.Text.ToUpper().Trim(), "2")
                    If dtfii.Rows.Count = 0 Then
                        b_dlMst = True
                    Else
                        lblError.Text = "此吊篮号有未使用完的记录，无法进行装配，请核查！"
                        Exit Sub
                    End If
                Else
                    lblError.Text = "未找到该吊篮号，请核查"
                    Exit Sub
                End If
            Else
                lblError.Text = "该吊篮号不属于法兰板的吊篮号，请核查"
                Exit Sub
            End If
        Else
            lblError.Text = "请扫描或输入吊篮号！"
            Exit Sub
        End If
        If dgvAssembling.Rows.Count < 1 Then
            lblError.Text = "请添加料框数量！"
            Exit Sub
        End If
        If b_dl And b_dlMst Then
            If txt_num.Value > 0 Then
                Dim operable_num = 0
                If txt_Max_Count.Value < txtAssemblableAll.Value Then
                    operable_num = txt_Max_Count.Value
                Else
                    operable_num = txtAssemblableAll.Value
                End If
                If txt_num.Value <= operable_num Then
                    If txt_current_all_num.Value <= operable_num Then
                        Dim flb_ingo As New entity_flb_info
                        'flb_ingo.sys_id = _sys_id
                        flb_ingo.dl_no = txtDLNo.Text.ToUpper().Trim()
                        flb_ingo.batch_no = dgvSelectedBatch
                        flb_ingo.pgd_id = String.Empty 'cmb_MesPlan.Tag.ToString()
                        flb_ingo.support_model = String.Empty
                        flb_ingo.material_code = cmbFLBMCode.Text.Trim()
                        flb_ingo.flb_type = dgvSelectedTV
                        flb_ingo.piece_num = txt_current_all_num.Value
                        If rdoZM.Checked Then
                            flb_ingo.which_side = "0"
                        Else
                            flb_ingo.which_side = "1"
                        End If
                        flb_ingo.status = "0"
                        flb_ingo.oper = cmbOper.Text.Trim()
                        Dim rtn As Integer
                        If dgvAssembling.Rows.Count = 1 Then
                            flb_ingo.b_gt_sys_id = dgv.SelectedRows(0).Cells("sys_id").Value.ToString()
                            rtn = objFlbInfo.save(flb_ingo)
                        ElseIf dgvAssembling.Rows.Count > 1 Then
                            'flb_ingo.b_gt_sys_id = dgv.SelectedRows(0).Cells("sys_id").Value.ToString()
                            flb_ingo.b_gt_sys_id = "0"
                            rtn = objFlbInfo.save(flb_ingo, dttemp)
                        End If
                        If rtn = -2 Then
                            lblError.Text = "保存失败"
                        Else
                            txtDLNo.Focus()
                            dttemp.Rows.Clear()
                            dgvAssembling.Refresh()
                            txt_num.Value = 0
                            txt_current_all_num.Value = 0
                            '写plc 满筐放行
                            If PLC_CONNECTED Then
                                If PLC.Write("DB30.DBX0.1", True).IsSuccess Then
                                    Threading.Thread.Sleep(1000)
                                    If PLC.Write("DB30.DBX0.1", False).IsSuccess = False Then
                                        PLC.Write("DB30.DBX0.1", False)
                                    End If
                                End If
                            End If
                            lblError.Text = "保存成功"
                            txtDLNo.Text = String.Empty
                            setData()
                            setDgvNgOperData()
                        End If
                    Else
                        lblError.Text = "当前料框已装配总数量 <= 单框可装配数量"
                    End If
                Else
                    If txt_Max_Count.Value < txtAssemblableAll.Value Then
                        lblError.Text = "装配数量需 <= 单框可装配数量"
                    Else
                        lblError.Text = "装配数量需 <= 总共可装配数量"
                    End If
                End If
            Else
                lblError.Text = "装配数量需 > 0"
            End If
        End If
    End Sub

    Private Sub btnMesWorkReport_Click(sender As Object, e As EventArgs) Handles btnMesWorkReport.Click
        Dim formMesWorkReport As New FormMesWorkReport()
        formMesWorkReport.usr = cmbOper.Text.Trim()
        formMesWorkReport.ShowDialog(Me)
    End Sub

    Private Sub btnMesWorkReportList_Click(sender As Object, e As EventArgs) Handles btnMesWorkReportList.Click
        Dim formMesWorkReportList As New FormMesWorkReportList()
        formMesWorkReportList.ShowDialog(Me)
    End Sub

    Private Sub btnAssemblingRecord_Click(sender As Object, e As EventArgs) Handles btnAssemblingRecord.Click
        Dim formAssemblingRecord As New FormAssemblingRecord()
        formAssemblingRecord.ShowDialog(Me)
    End Sub

    Private Sub btnDlHistoryRecord_Click(sender As Object, e As EventArgs) Handles btnDlHistoryRecord.Click
        Dim formFlbInfoList As New FormFlbInfoList()
        formFlbInfoList.ShowDialog(Me)
    End Sub

    Private Sub btnDlSearch_Click(sender As Object, e As EventArgs) Handles btnDlSearch.Click
        Dim formDlnfo As New FormDlnfo()
        formDlnfo.ShowDialog(Me)
    End Sub

    Private Sub btnUsedRecord_Click(sender As Object, e As EventArgs) Handles btnUsedRecord.Click
        Dim formUsedRecord As New FormUsedRecord()
        formUsedRecord.ShowDialog(Me)
    End Sub

    Private Sub btnFinish_Click(sender As Object, e As EventArgs) Handles btnFinish.Click
        If dgv.SelectedRows.Count > 0 Then
            If txtAssembledAll.Value + Decimal.Parse(dgvOKNG.Rows(0).Cells("Co_ng_num").Value.ToString()) = Decimal.Parse(dgvIntoAll.Rows(0).Cells("Col_oper_num").Value.ToString()) Then
                If String.IsNullOrEmpty(cmb_MesPlan.Tag.ToString()) = False Then
                    If MsgBox("请确认已装配完成，确认完工吗？", vbYesNo, "提示") = vbYes Then
                        Dim sys_id As String = dgv.SelectedRows(0).Cells("sys_id").Value.ToString()
                        Dim rtn As Integer = objGt.save("3", cmb_MesPlan.Tag.ToString(), sys_id)
                        If rtn <> -2 Then
                            '标记合格不合格结果
                            objGt.saveOkNg(sys_id)
                            '报工入库
                            'makeMesBgAndRk()
                            MsgBox("完工成功", vbYes, "提示")
                            setData()
                        Else
                            MsgBox("完工失败", vbYes, "提示")
                        End If
                    End If
                Else
                    MsgBox("未获取到生产计划信息，请进行生产设定", vbYes, "提示")
                End If
            Else
                MsgBox("请确保 入框总数 + 不合格总数 = 入料总数", vbYes, "提示")
            End If
        End If
    End Sub

    Private Sub makeMesBgAndRk()
        Dim b_gtSysId As String = dgv.SelectedRows(0).Cells("sys_id").Value.ToString()
        Dim b_gtPgdMesSysId As String = cmb_MesPlan.Tag.ToString()
        Dim dtPgdMesGt As DataTable = objPgdMesGt.getListById(b_gtPgdMesSysId)
        Dim b_gtPgdMesProjectCode As String = dtPgdMesGt.Rows(0)("mes_project_code").ToString()
        Dim dtGt As DataTable = objGt.getListById(b_gtSysId)
        Dim oper_num As String = dtGt.Rows(0)("ok_num").ToString()
        Dim oper_num_ng As String = dtGt.Rows(0)("ng_num").ToString()
        Dim b_gtPgdMes_gx As String = dtPgdMesGt.Rows(0)("material_code").ToString()
        '报工
        makeMesBg(b_gtSysId, b_gtPgdMesSysId, oper_num, oper_num_ng, b_gtPgdMes_gx, b_gtPgdMesProjectCode)
        'Dim oper_num As String = dgv.SelectedRows(0).Cells("Col_ok_num").Value.ToString()
        'Dim b_gtPgdMesProjectCode As String = dgv.SelectedRows(0).Cells("mes_project_code").Value.ToString()
        'Dim b_gtPgdMes_gx As String = dgv.SelectedRows(0).Cells("material_code_pgd").Value.ToString()
        '入库
        makeMesRk(oper_num, b_gtPgdMesProjectCode, b_gtPgdMes_gx)
    End Sub

    Private Sub makeMesBg(b_gtSysId As String, b_gtPgdMesSysId As String, oper_num As String, oper_num_ng As String, b_gtPgdMes_gx As String, b_gtPgdMesProjectCode As String)
        If dgv.SelectedRows.Count > 0 Then
            btnFinish.Enabled = False
            Dim dtGtPgdMesWorkReportOk As DataTable = objGtPgdMesWorkReport.getListByGtPgdmesSysId("ok", b_gtSysId)
            If dtGtPgdMesWorkReportOk.Rows.Count > 0 Then
                If MsgBox("此生产记录已报工过，确认要进行再次合格报工吗？", vbYesNo, "提示") = vbYes Then
                    objGtPgdMesWorkReport.insert("ok", b_gtSysId, b_gtPgdMesSysId, oper_num, cmbOper.Text.Trim())
                    Dim mes_bg_rtn00 As String = mesbg(oper_num, b_gtPgdMes_gx, b_gtPgdMesProjectCode)
                    Dim jo00 As JObject = JsonConvert.DeserializeObject(mes_bg_rtn00)
                    Dim code00 As String = jo00("code").ToString() '输出0
                    Dim msg00 As String = jo00("msg").ToString() '输出操作成功
                    If code00.Equals("0") Then
                        objGt.updatePgdMesWorkreportStatus(b_gtSysId, "1")
                        MsgBox("报工成功", vbYes, "提示")
                    Else
                        objGt.updatePgdMesWorkreportStatus(b_gtSysId, "-1")
                        MsgBox("报工失败：" & msg00, vbYes, "提示")
                    End If
                End If
            Else
                If MsgBox("确认要进行合格报工吗？", vbYesNo, "提示") = vbYes Then
                    objGtPgdMesWorkReport.insert("ok", b_gtSysId, b_gtPgdMesSysId, oper_num, cmbOper.Text.Trim())
                    Dim mes_bg_rtn As String = mesbg(oper_num, b_gtPgdMes_gx, b_gtPgdMesProjectCode)
                    Dim jo As JObject = JsonConvert.DeserializeObject(mes_bg_rtn)
                    Dim code As String = jo("code").ToString() '输出0
                    Dim msg As String = jo("msg").ToString() '输出操作成功
                    If code.Equals("0") Then
                        objGt.updatePgdMesWorkreportStatus(b_gtSysId, "1")
                        MsgBox("报工成功", vbYes, "提示")
                    Else
                        objGt.updatePgdMesWorkreportStatus(b_gtSysId, "-1")
                        MsgBox("报工失败：" & msg, vbYes, "提示")
                    End If
                End If
            End If
            Dim dtGtPgdMesWorkReportNg As DataTable = objGtPgdMesWorkReport.getListByGtPgdmesSysId("ng", b_gtSysId)
            If dtGtPgdMesWorkReportNg.Rows.Count > 0 Then
                If oper_num_ng.Equals("0") = False Then
                    If MsgBox("此生产记录已报工过，确认要进行再次不合格报工吗？", vbYesNo, "提示") = vbYes Then
                        objGtPgdMesWorkReport.insert("ng", b_gtSysId, b_gtPgdMesSysId, oper_num, cmbOper.Text.Trim())
                        Dim rtn_mes_bg11 As String = mesbgNg(oper_num_ng, b_gtPgdMes_gx, b_gtPgdMesProjectCode)
                        If String.IsNullOrEmpty(rtn_mes_bg11) = False Then
                            Dim jo11 As JObject = JsonConvert.DeserializeObject(rtn_mes_bg11)
                            Dim code11 As String = jo11("code").ToString() '输出0
                            Dim msg11 As String = jo11("msg").ToString() '输出操作成功
                            If code11.Equals("0") Then
                                objGt.updatePgdMesWorkreportStatus(b_gtSysId, "1")
                                MsgBox("报工成功", vbYes, "提示")
                            Else
                                objGt.updatePgdMesWorkreportStatus(b_gtSysId, "-1")
                                MsgBox("报工失败：" & msg11, vbYes, "提示")
                            End If
                        Else
                            MsgBox("未获取到报工返回信息", vbYes, "提示")
                        End If
                    End If
                Else
                    'MsgBox("不合格数量为0，无法进行不合格报工", vbYes, "提示")
                End If
            Else
                If oper_num_ng.Equals("0") = False Then
                    If MsgBox("确认要进行不合格报工吗？", vbYesNo, "提示") = vbYes Then
                        objGtPgdMesWorkReport.insert("ng", b_gtSysId, b_gtPgdMesSysId, oper_num, cmbOper.Text.Trim())
                        Dim rtn_mes_bg1X As String = mesbgNg(oper_num_ng, b_gtPgdMes_gx, b_gtPgdMesProjectCode)
                        If String.IsNullOrEmpty(rtn_mes_bg1X) = False Then
                            Dim jo1X As JObject = JsonConvert.DeserializeObject(rtn_mes_bg1X)
                            Dim code1X As String = jo1X("code").ToString() '输出0
                            Dim msg1X As String = jo1X("msg").ToString() '输出操作成功
                            If code1X.Equals("0") Then
                                objGt.updatePgdMesWorkreportStatus(b_gtSysId, "1")
                                MsgBox("报工成功", vbYes, "提示")
                            Else
                                objGt.updatePgdMesWorkreportStatus(b_gtSysId, "-1")
                                MsgBox("报工失败：" & msg1X, vbYes, "提示")
                            End If
                        Else
                            MsgBox("未获取到报工返回信息", vbYes, "提示")
                        End If
                    End If
                Else
                    'MsgBox("不合格数量为0，无法进行不合格报工", vbYes, "提示")
                End If
            End If
            btnFinish.Enabled = True
        End If
    End Sub

    Private Function mesbg(oper_num As String, productorname As String, b_gtPgdMesProjectCode As String) As String
        Dim params As String = "{"
        params &= """project_code"":""" & b_gtPgdMesProjectCode & """," 'mes合批号
        params &= """qualifiednumber"":""" & Double.Parse(oper_num) & """," '报工的合格数
        params &= """unqualifiednumber"":""" & 0.00 & """," '报工的不合格数
        params &= """productorname"":""" & productorname & """," '报工产品编码
        params &= """procedurename"":""" & "喷涂" & """," '报工工序
        params &= """compid"":""0de02b54-4e55-4dbf-ab89-f785df5f405c""," '公司id
        params &= """unqualifiedReason"":""" & "" & """" '不合格原因
        params &= "}"
        Return httpHelper.HttpPostWebService("dispatchingOrderBG", params)
    End Function

    Private Function mesbgNg(oper_num As String, productorname As String, b_gtPgdMesProjectCode As String) As String
        Dim rtn As String = String.Empty
        If dgv.SelectedRows.Count > 0 Then
            Dim dtGtNgDetails As DataTable = objGtNgDetails.getListByGtSysId(dgv.SelectedRows(0).Cells("sys_id").Value.ToString())
            For index = 0 To dtGtNgDetails.Rows.Count - 1
                Dim params As String = "{"
                params &= """project_code"":""" & b_gtPgdMesProjectCode & """," 'mes合批号
                params &= """qualifiednumber"":""" & 0.00 & """," '报工的合格数
                params &= """unqualifiednumber"":""" & Double.Parse(dtGtNgDetails.Rows(index)("ng_num").ToString()) & """," '报工的不合格数
                params &= """productorname"":""" & productorname & """," '报工产品编码
                params &= """procedurename"":""" & "喷涂" & """," '报工工序
                params &= """compid"":""0de02b54-4e55-4dbf-ab89-f785df5f405c""," '公司id
                params &= """unqualifiedReason"":""" & dtGtNgDetails.Rows(index)("ng_reason") & """" '不合格原因
                params &= "}"
                rtn = httpHelper.HttpPostWebService("dispatchingOrderBG", params)
            Next
        End If
        Return rtn
    End Function


    Private Sub makeMesRk(oper_num As String, b_gtPgdMesProjectCode As String, b_gtPgdMes_gx As String)
        If dgv.SelectedRows.Count > 0 Then
            Dim rtn As String = mesRk(oper_num, warehousecode, b_gtPgdMes_gx, b_gtPgdMesProjectCode)
            Dim jo As JObject = JsonConvert.DeserializeObject(rtn)
            Dim code As String = jo("code").ToString() '输出0
            Dim msg As String = jo("msg").ToString() '输出操作成功
            If code.Equals("0") Then
                MsgBox("MES入库成功", vbYes, "提示")
            Else
                MsgBox("MES入库失败：" & msg, vbYes, "提示")
            End If
        End If
    End Sub

    Private Function mesRk(oper_num As String, warehousecode As String, productorname As String, b_gtPgdMesProjectCode As String) As String
        Dim params As String = "{"
        params &= """project_code"":""" & b_gtPgdMesProjectCode & """," 'mes合批号
        params &= """rkcount"":""" & Double.Parse(oper_num) & """," '入库数量
        params &= """warehousecode"":""" & warehousecode & """," '入库仓库编码
        params &= """productorname"":""" & productorname & """," '产品编码
        params &= """procedurename"":""" & "喷涂" & """," '执行工序
        params &= """compid"":""0de02b54-4e55-4dbf-ab89-f785df5f405c""," '公司id
        params &= """departmentid"":""TS1103103""" '部门id
        params &= "}"
        Return httpHelper.HttpPostWebService("productFinishedToWarehouse", params)
    End Function

    Private Sub dgv_SelectionChanged(sender As Object, e As EventArgs) Handles dgv.SelectionChanged
        If dgv.SelectedRows.Count > 0 Then

        End If
    End Sub

    Private Sub cmbFLBType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbFLBType.SelectedIndexChanged
        If cmbFLBType.SelectedIndex > -1 Then

        End If
    End Sub

    Private Sub btnSet_Click(sender As Object, e As EventArgs) Handles btnSet.Click
        If String.IsNullOrEmpty(cmbFLBMCode.Text.Trim()) = False Then
            Dim formPlanMes As New FormPlanMes()
            formPlanMes.usr = cmbOper.Text.Trim()
            formPlanMes.ok_num = dgv.SelectedRows(0).Cells("ok_num").Value.ToString()
            formPlanMes.material_code = dgv.SelectedRows(0).Cells("material_code").Value.ToString()
            formPlanMes.ShowDialog(Me)
        Else
            MsgBox("请选择当前生产的法兰板", vbYes, "提示")
        End If
    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        Dim rtn As Integer = objWorkshopCurrent.updateDataClear("1", "FLBZP")
        If rtn = -2 Then
            MsgBox(btnClear.Text + "失败")
        Else
            MsgBox(btnClear.Text + "成功")
            initForm()
        End If
    End Sub

    Private Sub rdoZM_CheckedChanged(sender As Object, e As EventArgs) Handles rdoZM.CheckedChanged
        If String.IsNullOrEmpty(dgvSelectedTV) = False Then
            Dim dtFlbMst As DataTable = objFlbMst.selectFlbByVal(dgvSelectedTV)
            If rdoZM.Checked Then
                txt_Max_Count.Value = dtFlbMst.Rows(0)("count_down")
            End If
        End If
    End Sub

    Private Sub rdoFM_CheckedChanged(sender As Object, e As EventArgs) Handles rdoFM.CheckedChanged
        If String.IsNullOrEmpty(dgvSelectedTV) = False Then
            Dim dtFlbMst As DataTable = objFlbMst.selectFlbByVal(dgvSelectedTV)
            If rdoFM.Checked Then
                txt_Max_Count.Value = dtFlbMst.Rows(0)("count_up")
            End If
        End If
    End Sub

    Private Sub txt_num_MouseDown(sender As Object, e As MouseEventArgs) Handles txt_num.MouseDown
        UcDigitalKeyboard1 = New ucDigitalKeyboard
        If sender.MaskBox.Mask.EditMask = "d" Then
            UcDigitalKeyboard1.B_01 = False
        Else
            UcDigitalKeyboard1.B_01 = True
        End If

        If sender.GetType().Name.Equals("TextEdit") Then
            UcDigitalKeyboard1.B_02 = True
        Else
            UcDigitalKeyboard1.B_02 = False
        End If

        UcDigitalKeyboard1.Txt = sender

        Me.Controls.Add(UcDigitalKeyboard1)
        UcDigitalKeyboard1.Show()
        UcDigitalKeyboard1.BringToFront()
        UcDigitalKeyboard1.Focus()
    End Sub

    Private Sub FormMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If PLC_CONNECTED Then
            PLC.ConnectClose()
        End If
        Try
            resetEventPLC.Reset()
            If PLC_TH.IsAlive Then PLC_TH.Abort()
            If Scan0_TH.IsAlive Then Scan0_TH.Abort()
            objReader0 = Nothing
        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
    End Sub

    Private Sub FormMain_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        DBacs.Disconnect()
    End Sub

End Class


Public Class entity_flb_info
    Public sys_id As String
    Public batch_no As String
    Public factory_id As String
    Public dl_no As String
    Public pgd_id As String
    Public support_model As String
    Public material_code As String
    Public flb_type As String
    Public which_side As String
    Public piece_num As Integer
    Public used_piece_num As Integer
    Public status As String
    Public oper As String
    Public used_date As DateTime
    Public update_time As DateTime
    Public b_gt_sys_id As String
End Class

